<template>
  <!-- 表格------------------------------------------------------------------------------------- -->
  <el-dialog v-model="dialogFormVisible" width="1200px">
    <el-row :gutter="12" class="tableSelect">
      <el-col :span="16">
        <el-form
          :model="filterForm"
          ref="queryRef"
          :inline="true"
          label-width="120px"
          @submit.native.prevent
        >
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item :label="rowLabelText">
                <el-input
                  @change="handleQuery"
                  v-model="filterForm[rowLabel]"
                  clearable
                  style="width: 100%"
                  @keyup.enter="refresh"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-for="item in filterOp">
              <el-form-item :label="item.label">
                <el-input
                  @change="handleQuery"
                  v-model="filterForm[item.prop]"
                  clearable
                  style="width: 100%"
                  @keyup.enter="refresh"
                />
              </el-form-item>
            </el-col>
            <slot
              name="formSlot"
              :handleQuery="handleQuery"
              :filterForm="filterForm"
            ></slot>
            <el-col :span="5" style="text-align: right">
              <el-form-item>
                <el-button type="text" @click="refresh">搜索</el-button>
                <el-button type="text" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          ref="table"
          v-loading="state.loading"
          :data="state.list"
          @select="handleSelectionChange"
          height="500"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="selectable"
          />
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
            fixed="left"
          >
          </el-table-column>
          <template v-for="item in options">
            <el-table-column
              :prop="item.prop"
              :label="item.label"
              :min-width="item.width || 150"
              align="center"
            >
              <template #default="{ row }">
                {{ row[item.prop] }}
              </template>
            </el-table-column>
          </template>
          <slot name="tableSlot"></slot>
        </el-table>
        <pagination
          v-show="state.total > 0"
          :total="state.total"
          v-model:page="state.paginat.page"
          v-model:limit="state.paginat.size"
          @pagination="changePage"
        />
        <!-- changePage -->
      </el-col>
      <el-col :span="8">
        <div style="height: 50px" height="80px">已选中</div>
        <el-table
          ref="table"
          :data="selectData"
          @select="handleSelectionChange"
          height="500"
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
            fixed="left"
          >
          </el-table-column>
          <el-table-column
            prop="label"
            :label="rowLabelText"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="text" @click="del(scope)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="onConfirm"> 确 认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick } from "vue";
import { reactive, defineProps, defineEmits, defineExpose } from "vue";
const props = defineProps({
  queryApi: {
    type: Function,
    required: true,
  },
  maxNum: {
    type: Number,
    default: 100000,
  },
  options: {
    type: Array,
    default: () => [],
  },
  filterOp: {
    options: {
      type: Array,
      default: () => [],
    },
  },
  rowKey: {
    type: String,
    default: "id",
  },
  rowLabel: {
    type: String,
    default: "id",
  },
  rowLabelText: {
    type: String,
    default: "id",
  },
});
const table = ref();
const selectData = ref([]);
const emits = defineEmits(["onConfirm"]);
const dialogFormVisible = ref(false);
const handleQuery = () => {
  refresh();
};
const state = reactive({
  loading: true,
  list: [],
  total: 0,
  paginat: {
    page: 1,
    size: 15,
  },
  selectedList: [],
  filterForm: {},
});
const changePage = () => {
  state.loading = true;
  fetchData(state.paginat, done);
};
// const pagination = () => {
//   state.loading = true;
//   fetchData(state.paginat, done);
// };
// console.log(pagination);
const { filterForm } = toRefs(state);
const selectable = () => {
  return selectData.value.length < props.maxNum;
};
const del = (scope) => {
  selectData.value.splice(scope.$index, 1);
  changeSelection();
};
const changeSelection = () => {
  const keys = selectData.value.map((item) => item.value);
  const selected = state.list.filter((item) => {
    return keys.includes(item[props.rowKey] + "");
  });

  table.value.clearSelection();
  selected.forEach((row) => {
    table.value.toggleRowSelection(row);
  });
};
const done = (data) => {
  state.list = data.list;
  state.total = data.total;
  state.loading = false;
  nextTick().then(() => {
    changeSelection();
  });
};
const fetchData = (pageForm, done) => {
  props
    .queryApi({
      pageNum: pageForm.page,
      pageSize: pageForm.size,
      ...filterForm.value,
    })
    .then((res) => {
      done({
        list: res.rows,
        total: res.total,
      });
    });
};
const open = (data = []) => {
  selectData.value = data;
  dialogFormVisible.value = true;
  refresh(true);
};
const close = () => {
  dialogFormVisible.value = false;
};
const resetQuery = () => {
  filterForm.value = {};
  refresh(true);
};
const onConfirm = () => {
  emits("onConfirm", selectData.value, state.selectedList);
  close();
};
const handleSelectionChange = (selection, row) => {
  if (!!row) {
    const index = selection.findIndex(
      (item) => item[props.rowKey] == row[props.rowKey]
    );
    const index2 = selectData.value.findIndex(
      (item) => item.value == row[props.rowKey]
    );
    if (index != -1 && index2 == -1) {
      selectData.value.push({
        ...row,
        value: row[props.rowKey],
        label: row[props.rowLabel],
      });
    } else if (index == -1 && index2 != -1) {
      selectData.value.splice(index2, 1);
    }
  }
  state.selectedList = selection;
};
const refresh = (flag) => {
  if (flag) {
    state.paginat.page = 1;
  }
  state.loading = true;
  fetchData(state.paginat, done);
};

defineExpose({
  refresh,
  open,
});
</script>

<style lang="scss">
.tableSelect {
  .el-table__header {
    .el-checkbox.el-checkbox--default {
      display: none !important;
    }
  }
}
</style>
